import axios from "axios";
import qs from "qs";
import { isJSON } from "@/utils";
import { getToken } from "@/utils/auth";
import { Toast } from "vant";
// 重复请求拦截，需要进行请求路由判断，否则无法并发请求
var CancelToken = axios.CancelToken;
const pending = [];
const cancelPending = (config) => {
  pending.forEach((item, index) => {
    if (config) {
      if (item.UrlPath === config.url) {
        item.Cancel(); // 取消请求
        pending.splice(index, 1); // 移除当前请求记录
      }
    } else {
      item.Cancel(); // 取消请求
      pending.splice(index, 1); // 移除当前请求记录
    }
  });
};

// 基本实例
const service = axios.create({
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
  // baseURL: '/api'
});

service.interceptors.request.use(
  (request) => {
    const token = getToken();
    if (token) {
      request.headers["accessToken"] = token;
    }
    cancelPending(request);
    // 加入url判断是否重复请求
    request.cancelToken = new CancelToken((res) => {
      pending.push({ UrlPath: request.url, Cancel: res });
    });
    if (
      request.data &&
      request.headers["Content-Type"] === "application/x-www-form-urlencoded" &&
      Object.prototype.toString.call(request.data) === "[object Object]"
    ) {
      request.data = qs.stringify(request.data);
    }
    return request;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * @description 接口返回数据说明
 * @version 1.0.0
 * code 状态码 200 => success
 * msg 返回信息
 * data 请求数据
 */
// response 拦截器
service.interceptors.response.use(
  ({ data }) => {
    console.log("🚀 ~ data:", data);
    if (isJSON(data)) {
      data = JSON.parse(data);
    }
    if (data.success) {
      return data;
    }
    if (!data.success) {
      Toast.fail(data.message);
      return data;
    }
    if (data.code !== 200) {
      Toast.fail(data.message);
      return;
    }
    return data;
  },
  (error) => {
    if (error.message) {
      console.log("🚀 ~ error:", error);
      // Toast.fail(error.message);
      throw new Error(error.message);
    }
  }
);

export default service;
